import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import errorMessage from 'share/errorMessage';
import { Row, Col, message, Button } from 'antd';
import fullImg from 'images/fullVisible.png';

import travelService from 'containers/request/travel-request/travel.service'

class TravelOut extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      outSsoURL: '',
      callbackURL: ''
    };
  }

  componentWillMount(){}

  componentWillReceiveProps(nextProps){
    const { isOpenOutSlide } = this.props;
    if (!isOpenOutSlide && nextProps.isOpenOutSlide) {
      let params = {
        outItineraryCode: nextProps.outItem && nextProps.outItem.code,
        applicationOID: nextProps.oid,
        client: 'web'
      };
      if (nextProps.editOut) {
        params.outItineraryCode = nextProps.editOut.outItineraryCode;
        params.itineraryApprovalNumber = nextProps.editOut.itineraryApprovalNumber;
        params.outItineraryBusinessCode = nextProps.editOut.outItineraryBusinessCode;
      }
      travelService.getOutUrl(params).then(res => {
        this.setState({
          outSsoURL: res.data.ssoURL ? res.data.ssoURL : '',
          callbackURL: res.data.callbackURL ? res.data.callbackURL : ''
        }, this.openOut);
        if (!res.data || !res.data.ssoURL) {
          message.error(messages('request.key601')/*行程未配置有效访问地址。*/);
        }
      }).catch(err => {
        errorMessage(err.response);
      });
    }
    if (isOpenOutSlide && !nextProps.isOpenOutSlide) {
      //关闭外部行程 --> 调用后台触发中间件处理
      this.processCallBack();
    }
  }

  //打开外部行程的标签页
  openOut = () => {
    const { outSsoURL } = this.state;
    if (outSsoURL) {
      window.open(outSsoURL);
    }
  };

  processCallBack = () => {
    const { callbackURL } = this.state;
    const { callBack } = this.props;
    travelService.callBackOut(callbackURL).then(res => {
      console.log(res.data);
    }).catch(err => {
      errorMessage(err.response);
    }).finally(() => {
      if (callBack) {
        callBack({refresh: true}, 'out');
      }
      this.resetForm();
    });
  };

  //重置表单
  resetForm = () =>{
    this.setState({outSsoURL: '', callbackURL: ''});
  };

  closeOutSlide = () => {
    this.props.close();
  };

  render(){
    const { outSsoURL } = this.state;
    return (
      <div style={{height: 'calc(100% + 60px)'}}>
        <div style={{marginTop: 100, textAlign: 'center'}}>
          <img src={fullImg} style={{marginBottom: 50}} />
          <p>{messages('request.key639')/*请在弹出页面进行操作，完成后关闭此侧滑框即可。*/}</p>
        </div>
        <div className="slide-footer">
          <Button type="primary" onClick={this.closeOutSlide}>{messages('request.key102')/*关闭*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return { language: state.main.language };
}

export default connect(mapStateToProps)(TravelOut);
